package com.boxedinsoftware.betamax.smslite;

import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.net.URLEncoder;
import java.util.Calendar;

import org.xml.sax.InputSource;
import org.w3c.dom.*;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.util.Log;
import android.widget.Toast;
public class SendSMSService extends Service {
	
	private NotificationManager mNotificationManager = null;
	private NotificationManager mNotificationManager1 = null;
	private static final int SENDING_ID = 1;
	private static final int SENT_ID = 2;
	private static final String TAG = "Betamax SMS Lite";
	private static int count = 1;
	SharedPreferences preferences;
	
	String number;
	String text;

	@Override
	public void onCreate() {
		//Toast.makeText(this, "My Service Created", Toast.LENGTH_LONG).show();
		Log.d(TAG, "Service Created");
		
		
	}

	@Override
	public void onDestroy() {
		//Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();
		Log.d(TAG, "Service Stopped");
		
	}
	
	@Override
	public void onStart(Intent intent, int startid) {
		Toast.makeText(this, "Sending Betamax SMS Lite", Toast.LENGTH_LONG).show();
		startOngoingNotification();
		Log.d(TAG, "Service Started");
		Bundle bundle = intent.getExtras();
		number = bundle.getString("number");
		String provider = bundle.getString("provider");
		String username = bundle.getString("username");
		String password = bundle.getString("password");
		text = bundle.getString("text");
		count = bundle.getInt("count");
		
		preferences = PreferenceManager.getDefaultSharedPreferences(this);
		String[] params = {provider , username , password, number, "9" , text , "" + count};
		new SMSsend().execute(params);
    
	
    /*if(error == true)
    {
    	
    	startStatusNotification("Betamax SMS" , "Status - " + entityContents , "Betamax SMS not sent");
    	
    }
    else
    {
    	
    	
    	startStatusNotification("Betamax SMS" , "Status - " + entityContents , "Betamax SMS Successful");
    	
    }
	
		
		
		
	
	}*/
	}
	
	public void startOngoingNotification()
	{
		String ns = Context.NOTIFICATION_SERVICE;
		mNotificationManager = (NotificationManager) getSystemService(ns);
		
		int icon = com.boxedinsoftware.betamax.smslite.R.drawable.betamaxsms72;
		CharSequence tickerText = "Betamax SMS Lite Sending Message";
		long when = System.currentTimeMillis();

		Notification notification = new Notification(icon, tickerText, when);

		notification.flags |= Notification.FLAG_ONGOING_EVENT;
		
		Context context = getApplicationContext();
		CharSequence contentTitle = "Betamax SMS Lite";
		CharSequence contentText = "Sending SMS ...";
		PendingIntent contentIntent = PendingIntent.getActivity(this, 0, null, 0);

		notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
		
		
		

		mNotificationManager.notify(SENDING_ID, notification);
		
		
	}
	
	
	public void startStatusNotification(String title, String message , String ticker)
	{
		String ns = Context.NOTIFICATION_SERVICE;
		mNotificationManager1 = (NotificationManager) getSystemService(ns);
		
		int icon = com.boxedinsoftware.betamax.smslite.R.drawable.betamaxsms72;
		CharSequence tickerText = ticker;
		long when = System.currentTimeMillis();

		Notification notification = new Notification(icon, tickerText, when);
		notification.flags |= Notification.FLAG_AUTO_CANCEL;
		
		if(preferences.getBoolean("sentVibrate", true) == true)
		{
			
			notification.flags |= Notification.DEFAULT_VIBRATE;
			
			
		}
		
		
		Context context = getApplicationContext();
		CharSequence contentTitle = title;
		CharSequence contentText =  message;
		PendingIntent contentIntent = PendingIntent.getActivity(this, 0, null, 0);

		notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
		
		

		mNotificationManager1.notify(SENT_ID, notification);
		
		
	}

	@Override
	public IBinder onBind(Intent arg0) {
		return null;
	}
	
	
	public class SMSsend extends AsyncTask<String, Void, String> {
		
		protected String[] params;
		
		@Override
		protected String doInBackground(String... params) {
			try{
	    		this.params = params;
				
				String number = params[3];
				String sourceNumberString = preferences.getString("ownNumber", "0");
					
				
				number = number.replaceAll( "-", "" );
	            number = number.replace(")", "");
	            number = number.replace("(", "");
	            number = number.replaceAll(" ", "");
	            number = number.replaceAll("[a-z,A-Z]", "");
				
				//Log.e("providerString", providerString);
	            String entityContents = "";
			    HttpClient httpclient = new DefaultHttpClient();  
			    String line = "";
			    int start = 0;
			    int end = 0;
			    for(int i = 1; i <= count ; i++)
			    {
			   
			    if(i == 1 && i != count){
			    	start = 0;
			    	end = 160;
			    }
			    else if(i != count){
			    	
			    	start = end;
			    	end = (i * 160);
			    }
			    else
			    {
			    
			    	start = end;
			    	end = text.length();
			    	
			    }
			    line = text.substring(start, end);
			    String url = "https://www."+params[0]+"/myaccount/sendsms.php?username="+params[1].trim()+"&password="+params[2].trim()+"&from="+ sourceNumberString +"&to="+number+"&text="+ URLEncoder.encode(line, "UTF-8").toString();
			    HttpGet httpget = new HttpGet(url);
			    Log.e("URL", httpget.getURI().toString());
			    
	  
	            HttpResponse response = httpclient.execute(httpget);  
	            
	            byte buffer[] = new byte[1024] ;
				InputStream is = response.getEntity().getContent() ;
				int numBytes = is.read(buffer) ;
				is.close();
				
				entityContents = new String(buffer,0,numBytes) ;
			    }
					

					
		            
				 return entityContents;   
				
				
				
				
		            
		           
		            
	            
	            
	            
	            
	              
	        } catch (ClientProtocolException e) {  
	        	
	        	return("error");
	        	//return e.getMessage();
	        } catch (IOException e) {  
	        	
	        	//return e.getMessage();
	        	return("error");
	        	
	        } 
	        
	       
		}

		/* (non-Javadoc)
		 * @see android.os.AsyncTask#onPostExecute(java.lang.Object)
		 */
		@Override
		protected void onPostExecute(String result) {

			mNotificationManager.cancelAll();
			
		   if(result.equalsIgnoreCase("error"))
		   {
			   
			   startStatusNotification("Betamax SMS Lite" , "Status - Not sent - Connection error" , "Betamax SMS not sent");
			   Toast.makeText(SendSMSService.this.getApplicationContext(), "Betamax SMS not sent. Message saved as draft.", Toast.LENGTH_LONG).show();
			   
		   }
		   else
		   {
			   
			   int versionCode = 0;
			   int statusCode = 0;
			   String status = "";
			   String cause = "";
			   
			   try {
			        DocumentBuilderFactory dbf =
			            DocumentBuilderFactory.newInstance();
			        DocumentBuilder db = dbf.newDocumentBuilder();
			        InputSource is = new InputSource();
			        is.setCharacterStream(new StringReader(result));

			        Document doc = db.parse(is);
			        NodeList nodes = doc.getElementsByTagName("SmsResponse");

			        // iterate the employees
			       
			           Element element = (Element) nodes.item(0);

			           NodeList version = element.getElementsByTagName("version");
			           Element line = (Element) version.item(0);
			           versionCode = Integer.parseInt(getCharacterDataFromElement(line));

			           NodeList resultCode = element.getElementsByTagName("result");
			           line = (Element) resultCode.item(0);
			           statusCode = Integer.parseInt(getCharacterDataFromElement(line));
			           
			           NodeList resultstring = element.getElementsByTagName("resultstring");
			           line = (Element) resultstring.item(0);
			           status = getCharacterDataFromElement(line);
			           
			           NodeList description = element.getElementsByTagName("description");
			           line = (Element)description.item(0);
			           cause = getCharacterDataFromElement(line);
			        
			    }
			    catch (Exception e) {
			        e.printStackTrace();
			    }

			   if(statusCode == 1){
			   startStatusNotification("Betamax SMS Lite" , "Status : " + statusCode + " - " + status , "Betamax SMS");
			   if(preferences.getBoolean("integration", true) == true){
			   ContentValues values = new ContentValues();
	           values.put(SendSMS.ADDRESS, number);
	           values.put(SendSMS.DATE, "" + Calendar.getInstance().getTimeInMillis());
	           values.put(SendSMS.READ, 1);
	           values.put(SendSMS.STATUS, -1);
	           values.put(SendSMS.TYPE, 2);
	           values.put(SendSMS.BODY, text);

	           getContentResolver().insert(Uri.parse("content://sms"), values);
	           SharedPreferences.Editor editor = preferences.edit();
		        editor.putString("draftNumber", "");
		        editor.putString("draftMessage", "");
		        editor.commit();
			   }
			   }
			   else{
				   
				   startStatusNotification("Betamax SMS failed" , "Status : " + status + " - " + cause , "Betamax SMS not sent");
				   Toast.makeText(SendSMSService.this.getApplicationContext(), "Betamax SMS not sent. Message saved as draft.", Toast.LENGTH_LONG).show();
				   
			   }
			   
		   }
	       
	        
	        
	        
	        
	    	 
			
			super.onPostExecute(result);
			
			SendSMSService.this.stopSelf();
		}

		/* (non-Javadoc)
		 * @see android.os.AsyncTask#onPreExecute()
		 */
		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
		}

		/* (non-Javadoc)
		 * @see android.os.AsyncTask#onProgressUpdate(Progress[])
		 */
		@Override
		protected void onProgressUpdate(Void... values) {
			// TODO Auto-generated method stub
			super.onProgressUpdate(values);
		}

	}
	
	public static String getCharacterDataFromElement(Element e) {
	    Node child = e.getFirstChild();
	    if (child instanceof CharacterData) {
	       CharacterData cd = (CharacterData) child;
	       return cd.getData();
	    }
	    return "?";
	  }

}
